package com.hdu.controller;


import com.hdu.common.Result;
import com.hdu.common.ResultCode;
import com.hdu.exception.CustomException;
import com.hdu.pojo.User;
import com.hdu.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/login")
    public Result<String> login(String username,String password){
//        System.out.println(username);
        if (username==null||password==null){
            throw new CustomException("用户密码值为空，发送未知错误！");
        }

        if(!userService.login(username,password)){
            throw new CustomException("登录失败,错误！");
        }

        return new Result<>(ResultCode.SUCCESS,"登录成功！");
    }

    @PostMapping("/register")
    public Result<String> register(String username,String password){
        if (username == null || password == null ||
                username.isEmpty() || password.isEmpty()){
            throw new CustomException("用户密码值为空，发送未知错误！");
        }

        if (!userService.register(username,password)){
            throw new CustomException("注册失败");
        }

        return new Result<>(ResultCode.SUCCESS,"注册成功！");
    }

    @GetMapping("/registerByPhone")
    public Result<String> registerByPhone(String phone, HttpSession session){
        boolean isSuccess = userService.generateCode(phone, session);
        return new Result<>(ResultCode.SUCCESS,"验证码以发送，有效期2分钟");
    }

    @GetMapping("/processRegisterByPhone")
    public Result<String> processRegisterByPhone(String phone,String code){
        boolean isSuccess = userService.confirmCode(phone,code);

        return new Result<>(ResultCode.SUCCESS,"注册成功！登录成功！");
    }

    @GetMapping("/loginByPhone")
    public Result<String> loginByPhone(String phone,String code){

        return userService.loginByPhone(phone,code);
    }

    @GetMapping("/test")
    public String TestMethod(){
        System.out.println("你知道的，我是为了测试!");
        log.info("测试测试");
        return "你知道的，我是为了测试!";
    }
}
